package com.example.bluetoothtest;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;


public class ConnectAndDisconnectActivity extends AppCompatActivity {

    // 新增成员变量
    private BluetoothAdapter bluetoothAdapter;
    private String deviceAddress;
    private String deviceName;
    private Button start_test;
    private EditText test_time, dis_time, wait_time;
    private TextView textView;
    private Thread currentThread; // 用于存储当前线程
    private Handler handler = new Handler();
    private ConnectManager connectManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        deviceName = getIntent().getStringExtra("bluetooth_name");
        // 存储MAC地址
        deviceAddress = getIntent().getStringExtra("bluetooth_address");
        ((TextView) findViewById(R.id.device_name)).setText("设备名称：" + deviceName + "\n" + "MAC地址：" + deviceAddress);

        // 新增初始化
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        connectManager = new ConnectManager(bluetoothAdapter, deviceAddress);
        connectManager.initProfiles(this);

        // 控件初始化
        // 开始按键
        start_test = findViewById(R.id.start_test);
        // 次数
        test_time = findViewById(R.id.test_times);
        // 断连时间
        dis_time = findViewById(R.id.dis_times);
        // 间隔时间
        wait_time = findViewById(R.id.wait_times);
        // 日志textview
        textView = findViewById(R.id.tv_log);
        textView.setText(textView.getText(), TextView.BufferType.EDITABLE);
        textView.setMovementMethod(new ScrollingMovementMethod());

        // 设置默认值
        test_time.setText("10"); // 默认测试次数
        dis_time.setText("10");   // 默认断连时间
        wait_time.setText("15");  // 默认间隔时间

        // 按钮点击事件
        start_test.setOnClickListener(v -> ConnectAndDisconnect());

        // 注册广播接收器
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 终止当前线程
        if (currentThread != null && currentThread.isAlive()) {
            currentThread.interrupt();
            try {
                currentThread.join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                Log.e("TEST", "线程中断", e);
            }
        }
        connectManager.disconnectDevice(() -> {});

        // 取消注册广播接收器
        unregisterReceiver(bluetoothReceiver);
    }


    private void ConnectAndDisconnect() {
        // 获取测试次数
        String get_times = test_time.getText().toString().trim();
        // 获取间隔时间
        String w_time = wait_time.getText().toString().trim();
        // 获取断连时间
        String d_time = dis_time.getText().toString().trim();

        if (!get_times.isEmpty()) {
            try {
                // 验证并解析测试次数，如果未提供，则使用默认值
                int g_times = validateInput(get_times, "测试次数", 10); // 默认值为10次
                // 验证并解析断开时间，如果未提供，则使用默认值
                int dc_time = validateInput(d_time, "断连时间", 5) * 1000; // 默认值为5秒
                // 验证并解析间隔时间，如果未提供，则使用默认值
                int wa_time = validateInput(w_time, "间隔时间", 3) * 1000; // 默认值为3秒

                // 终止旧线程
                stopCurrentThread();

                // 开启新线程
                currentThread = new Thread(() -> {
                    textView.setText("");
                    scrollToTop();

                    for (int i = 1; i <= g_times; i++) {
                        final int currentIteration = i;

                        // 更新UI
                        updateTimeUI(currentIteration, g_times);
                        //等到断连的时间
                        int wat_time = wa_time - dc_time;

                        // 尝试连接设备
                        runOnUiThread(() -> connectManager.connectDevice(() -> {
                            // 检查连接状态
                            checkConnectStatus(currentIteration, dc_time);
                            if (connectManager.isConnected()) {
                                //如果已连接则延迟后断开
                                handler.postDelayed(() -> {
                                   runOnUiThread(() -> connectManager.disconnectDevice(() -> {
                                       //持续检查断开连接状态
                                       checkDisconnectStatus(currentIteration, wat_time);
                                   }));
                                }, dc_time);
                            } else {
                                //如果未连接，则提示未连接信息，跳过盖该次断连操作
                                logAndAppend("第" + currentIteration + "次连接失败，即将进入下一次连接", false);
                            }
                        }));

                        //等待本次测试完成
                        try {
                            Thread.sleep(wa_time);
                        } catch (InterruptedException e) {
                            handleInterruptedException(e);
                        }

                        // 检查线程是否被中断
                        if (Thread.currentThread().isInterrupted()) {
                            logAndAppend("线程被中断，提前结束", false);
                            break;
                        }
                    }
                    // 测试完成后更新UI
                    runOnUiThread(() -> {
                        Toast.makeText(this, "执行 " + g_times + " 次结束", Toast.LENGTH_SHORT).show();
                    });
                });
                currentThread.start();

            } catch (IllegalArgumentException e) {
                runOnUiThread(() -> {
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }
    }

    //检查连接状态
    private void checkConnectStatus(int iteration, int dc_time) {
        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTime < dc_time) {
            if (connectManager.isConnected()) {
                logAndAppend("第 " + iteration + "次连接成功", true);
                return;
            }
            try {
                Thread.sleep(500); // 每隔500毫秒检查一次
            } catch (InterruptedException e) {
                handleInterruptedException(e);
                return;
            }
        }
        logAndAppend("第 " + iteration + "次连接超时", false);
    }

    private void checkDisconnectStatus(int iteration, int wat_time) {
        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTime < wat_time) {
            if (connectManager.isDisconnected()) {
                logAndAppend("第 " + iteration + "次断开成功", true);
                return;
            }
            try {
                Thread.sleep(500); // 每隔500毫秒检查一次
            } catch (InterruptedException e) {
                handleInterruptedException(e);
                return;
            }
        }
        logAndAppend("第 " + iteration + "次断连超时", false);
    }


    // 停止当前线程
    private void stopCurrentThread() {
        if (currentThread != null && currentThread.isAlive()) {
            currentThread.interrupt();
            try {
                currentThread.join(1000); // 等待最多1秒
            } catch (InterruptedException e) {
                handleInterruptedException(e);
            }
        }
    }

    // 输入验证方法
    private int validateInput(String input, String fieldName, int defaultValue) {
        try {
            int value = Integer.parseInt(input);
            if (value <= 0) {
                throw new IllegalArgumentException(fieldName + "必须大于0");
            }
            return value;
        } catch (NumberFormatException e) {
            Log.w("INPUT_VALIDATION", fieldName + "无效，使用默认值: " + defaultValue);
            return defaultValue;
        }
    }

    // 处理中断异常
    private void handleInterruptedException(InterruptedException e) {
        Thread.currentThread().interrupt();
        Log.e("TEST", "线程中断", e);
    }

    // 格式化日志
    private SpannableString formatLog(String message, boolean isSuccess) {
        String fullMessage = message + "\n";
        SpannableString spannableString = new SpannableString(fullMessage);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(
                isSuccess ? ContextCompat.getColor(this, R.color.success)
                        : ContextCompat.getColor(this, R.color.failure)
        );
        spannableString.setSpan(colorSpan, 0, fullMessage.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        return spannableString;
    }

    // 更新日志
    private void updateLog(SpannableString log) {
        runOnUiThread(() -> {
            textView.append(log);
            scrollToBottom();
        });
    }

    // 新增方法用于统一处理日志输出
    private void logAndAppend(String message, boolean isSuccess) {
        Log.d("Bluetooth", message);
        runOnUiThread(() -> updateLog(formatLog(message, isSuccess)));
    }

    private void updateTimeUI(int i, int total_times) {
        runOnUiThread(() -> {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = sdf.format(new java.util.Date());
            Editable editable = (Editable) textView.getText();
            editable.append(formattedDate + " [" + i + "/" + total_times + "]\n");
            scrollToBottom();
        });
    }

    // 日志滚动到底部方法
    private void scrollToBottom() {
        textView.post(() -> {
            int offset = textView.getLineCount() * textView.getLineHeight();
            if (offset > textView.getHeight()) {
                textView.scrollTo(0, offset - textView.getHeight());
            }
        });
    }

    //日志滚动到顶部方法
    private void scrollToTop() {
        textView.post(() -> {
            textView.scrollTo(0, 0);
        });
    }

    // 广播接收器
    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                // 在广播接收器中调用
                runOnUiThread(() -> {
                    Log.d("Bluetooth", "设备已连接: " + device.getName());
                    logAndAppend("设备已连接: " + device.getName(), true);
                });
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                runOnUiThread(() -> {
                    Log.d("Bluetooth", "设备已断开: " + device.getName());
                    logAndAppend("设备已断开: " + device.getName(), true);
                });
            }
        }
    };
}
